/*
 *
 *  Copyright (C) 2012-2024
 *  All rights reserved, Designed By 杭州连线客信息技术有限公司
 *  注意：
 *  本软件为杭州连线客信息技术有限公司开发研制，未经购买不得使用
 *  购买后可获得全部源代码（禁止转卖、分享、上传到码云、github等开源平台）
 *  一经发现盗用、分享等行为，将追究法律责任，后果自负
 *
 */

package com.lxk.oms.flow.order;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import com.lxk.oms.cart.domain.vo.OmsCartVo;
import com.lxk.oms.cart.service.IOmsCartService;
import com.lxk.oms.order.domain.req.CreateOrderReq;
import com.yomahub.liteflow.annotation.LiteflowComponent;
import com.yomahub.liteflow.core.NodeComponent;
import lombok.AllArgsConstructor;
import org.dromara.common.core.exception.ServiceException;

import java.util.List;

/**
 * 单商家-购物车下单
 *
 * @author heyi
 * 2024/9/23
 */
@LiteflowComponent(value = FlowOrderNodeConst.CART_CREATE_ORDER)
@AllArgsConstructor
public class OrderCartNode extends NodeComponent {
    private final IOmsCartService omsCartService;

    @Override
    public void beforeProcess() {
        CreateOrderReq params = this.getRequestData();
        List<Long> cartIdList = params.getCartIdList();
        if (CollUtil.isEmpty(cartIdList)) {
            throw new ServiceException("请选择购物车商品");
        }
        Long userId = params.getUserId();
        List<OmsCartVo> cartList = omsCartService.queryByIdList(cartIdList, userId);
        if (CollUtil.isEmpty(cartList)) {
            throw new ServiceException("请选择购物车商品");
        }
        OrderContext contextBean = this.getContextBean(OrderContext.class);
        contextBean.setCartList(cartList);
    }

    @Override
    public void process() throws Exception {
        CreateOrderReq params = this.getRequestData();
        OrderContext contextBean = this.getContextBean(OrderContext.class);
        Long merId = params.getMerId();
        List<OmsCartVo> cartList = contextBean.getCartList();
        List<CreateOrderReq.CreateOrderItem> orderItemList = cartList.stream().map(item -> {
            Long skuId = item.getSkuId();
            Integer count = item.getCount();
            CreateOrderReq.CreateOrderItem createOrderItem = new CreateOrderReq.CreateOrderItem();
            createOrderItem.setCount(count);
            createOrderItem.setSkuId(skuId);
            createOrderItem.setMerId(merId);
            return createOrderItem;
        }).toList();
        params.setCreateOrderItemList(orderItemList);

    }

    @Override
    public boolean isAccess() {
        CreateOrderReq params = this.getRequestData();
        return ObjectUtil.equal(CreateOrderReq.CreateType.CART, params.getCreateType());
    }
}
